<template>
  <!-- 代取东西  待修改 -->
  <div style="height: 100%">
    <div class="search" style="display: flex; margin-left: 10px">
      <el-input
        v-model="search"
        placeholder="请输入搜索内容"
        style="width: 200px"
      ></el-input
      ><el-button
        icon="el-icon-search"
        circle
        style="margin-left: 20px"
        @click="searchData(search)"
      ></el-button>
      <el-button
        icon="el-icon-plus"
        circle
        style="margin-left: 20px; color: #9bc9d3"
        @click="addInfo = true"
        v-if="identity && userAudit == 'true'"
      ></el-button>
    </div>
    <div
      class="content"
      v-loading="tableData.length <= 0"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-row>
        <el-col
          :span="4"
          v-for="(item, index) in tableData"
          :key="index"
          style="padding: 10px"
          v-if="dateCompare(item)"
        >
          <!-- v-if="dateCompare(item)" -->
          <el-card :body-style="{ padding: '5px' }" shadow="hover">
            <img :src="item.takeImg" class="image" height="150px" />
            <div style="padding: 14px">
              <el-tag effect="dark" style="border: none; height: 28px"
                >代取
                <!-- {{ item.takeType }} -->
              </el-tag>
              <span> {{ item.takeTitle }} </span>
              <div class="bottom clearfix">
                <textarea v-model="item.takeDesc" class="desc" style="">
                </textarea>
                <!-- <span class="desc"
                  >{{item.desc}}</span
                ><br> -->
                <span class="time">有效时间：{{ item.takeValidDate }}</span>
                <span class="time" v-if="item.takeContact"
                  >联系方式：{{ item.takeContact }}</span
                >
                <div class="tags">
                  <el-tag
                    :type="item.takeTagType"
                    v-for="(tag, index) in item.takeTags.slice(0, 6)"
                    :key="index"
                    >{{ tag }}</el-tag
                  >
                </div>

                <el-button type="text" class="button" @click="showDetail(item)"
                  >查看详细信息</el-button
                >
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 信息展示弹框 -->
      <el-dialog title="信息详情" :visible.sync="dialogFormVisible" center>
        <template>
          <div
            style="
              top: 20px;
              left: 30px;
              position: absolute;
              width: 42px;
              height: 20px;
              text-align: center;
              background: #f56c6c;
              color: white;
            "
            @click="jubao(form)"
          >
            举报
          </div>
        </template>
        <el-form :model="form">
          <el-form-item label="物品图片" :label-width="formLabelWidth">
            <template v-for="(item, index) in form.img" v-bind="index">
              <img
                :src="item.takeImg"
                alt=""
                height="200px"
                width="200px"
                style="margin: 0 5px"
              />
            </template>
          </el-form-item>
          <el-form-item label="物品名称" :label-width="formLabelWidth">
            <el-input
              v-model="form.takeTitle"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="相关描述" :label-width="formLabelWidth">
            <el-input
              v-model="form.takeDesc"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="标签" :label-width="formLabelWidth">
            <el-tag
              :type="form.takeTagType"
              v-for="(tag, index) in form.takeTags"
              :key="index"
              style="margin-left: 10px"
              >{{ tag }}</el-tag
            >
          </el-form-item>
          <el-form-item label="有效时间" :label-width="formLabelWidth">
            <el-input
              v-model="form.takeValidDate"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系方式" :label-width="formLabelWidth">
            <el-input
              v-model="form.takeContact"
              autocomplete="off"
              :disabled="true"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <template>
            <el-button type="primary" @click="takeMessage(form)"
              >给 Ta 留 言</el-button
            >
          </template>
        </div>
      </el-dialog>
      <!-- 信息添加弹框 -->
      <el-dialog
        title="添加信息"
        :visible.sync="addInfo"
        center
        @close="hidden"
      >
        <el-form :model="addform" ref="addForm" :rules="rules">
          <el-form-item label="物品图片" :label-width="formLabelWidth">
            <el-upload
              action=""
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- 图片预览 -->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <!-- <img :src="addform.img" alt="" height="200px" width="200px" /> -->
          </el-form-item>
          <el-form-item label="事件属性" :label-width="formLabelWidth">
            <div>
              <el-radio v-model="addform.tagType" label="" border disabled
                >代取</el-radio
              >
            </div>
          </el-form-item>
          <el-form-item
            label="物品名称"
            :label-width="formLabelWidth"
            required
            prop="title"
          >
            <!--               :fetch-suggestions="queryTitleSearch" -->
            <el-autocomplete
              v-model="addform.title"
              placeholder="请输入物品名称"
              :trigger-on-focus="false"
              :fetch-suggestions="queryTitleSearch"
              @select="handleSelect"
              @blur="addTag(addform.title)"
              props="title"
            ></el-autocomplete>
          </el-form-item>
          <!--               :fetch-suggestions="queryPlaceSearch" -->
          <el-form-item label="地点" :label-width="formLabelWidth">
            <el-autocomplete
              v-model="addform.place"
              placeholder="请输入地点"
              :trigger-on-focus="false"
              :fetch-suggestions="queryPlaceSearch"
              @select="handleSelect"
              @blur="addTag(addform.place)"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item
            label="相关描述"
            :label-width="formLabelWidth"
            prop="desc"
          >
            <el-input
              type="textarea"
              :rows="2"
              placeholder="有同学可以帮忙带个东西从宜宾到在自贡？详情请联系我，非常感谢"
              v-model="addform.desc"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="标签" :label-width="formLabelWidth">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              :type="addform.tagType"
              @close="handleClose(tag)"
              style="margin-right: 5px"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-tooltip
              class="item"
              effect="dark"
              content="标签尽可能清楚，以便查找"
              placement="top-start"
              v-else
            >
              <el-button class="button-new-tag" size="small" @click="showInput"
                >+ New Tag</el-button
              >
            </el-tooltip>
          </el-form-item>
          <el-form-item
            label="有效时间"
            :label-width="formLabelWidth"
            prop="validDate"
          >
            <div class="block">
              <el-date-picker
                v-model="addform.validDate"
                type="datetime"
                placeholder="选择日期时间"
                align="right"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                style="width: 300px"
              >
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="联系方式" :label-width="formLabelWidth">
            <el-input
              v-model="addform.contact"
              autocomplete="off"
              placeholder="请输入联系方式"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addInfo = false">取 消</el-button>
          <el-button type="primary" @click="add('addForm', addform)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <!-- //分页动态显示 -->
    <div class="pages">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[12]"
        :page-size="12"
        layout="total, prev, pager, next, jumper"
        :total="totalData"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      search: "",
      currentPage: 1,
      nowData: this.formatDate(new Date()),
      totalData: 0,
      // 每页内容数据
      tableData: [],
      //总数据
      tableData1: [],
      // 详细信息弹框
      dialogFormVisible: false,
      form: {},
      formLabelWidth: "100px",
      // 添加信息
      addInfo: false,
      addform: {
        tagType: "",
        validDate: this.formatDate(new Date()),
      },
      // 图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 图片列表
      fileList: [],
      loadAllTitle: [
        { value: "一卡通" },
        { value: "计算器" },
        { value: "教科书" },
        { value: "晾衣架" },
        { value: "布偶" },
        { value: "吉他" },
      ],
      loadAllPlace: [
        { value: "图书馆" },
        { value: "一期操场" },
        { value: "令雅食堂" },
        { value: "A10栋" },
        { value: "B12栋" },
        { value: "万达广场" },
      ],
      rules: {
        title: [{ required: true, message: "请输入", trigger: "blur" }],
        validDate: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        desc: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      // 新tag
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      // 是否登录
      identity: "",
      userAudit:""
    };
  },
  created() {
    this.identity = window.sessionStorage.getItem("identity");
    this.userAudit = window.sessionStorage.getItem("userAudit");
    // console.log(window.sessionStorage.getItem("userName"), "yonghu");
    // console.log(window.sessionStorage.getItem("userId"), "yonghu");
    // 获取数据
    this.getData();
    /*分页：
    1:1,12
    2:13,24，
    3：25,36
    n: n-1*12+1 ，12n */
  },
  mounted() {},
  methods: {
    // 获取所有数据
    getData() {
      var that = this;
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/take/takeList",
      })
        .then((res) => {
          if (res.data.code == 200) {
            console.log(res.data.data);
            that.tableData1 = res.data.data;
          } else {
            console.log("error", res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      setTimeout(() => {
        for (let index = 0; index < that.tableData1.length; index++) {
          that.tableData1[index].tagType = "";
          if (typeof that.tableData1[index].takeTags == "string") {
            var chars = that.tableData1[index].takeTags.split(",");
            that.tableData1[index].takeTags = chars;
          } else if (that.tableData1[index].takeTags == null) {
            that.tableData1[index].takeTags = ["暂无标签"];
          }
        }
        // console.log(that.tableData1[3].takeTags);
        this.tableData = this.tableData1.slice(0, 12);
        this.totalData = this.tableData1.length;
      }, 200);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.tableData = this.tableData1.slice(
        (this.currentPage - 1) * 12,
        this.currentPage * 12
      );
    },
    // 时间处理
    formatDate(date) {
      var year = date.getFullYear();
      var month = this.format(date.getMonth() + 1);
      var day = this.format(date.getDate());
      var h = this.format(date.getHours());
      var m = this.format(date.getMinutes());
      return year + "-" + month + "-" + day + " " + h + ":" + m;
    },
    format(val) {
      return Number(val) < 10 ? "0" + val : "" + val;
    },
    dateCompare(item) {
      var date1 = new Date(item.takeValidDate);
      var date2 = new Date(this.nowData);
      if (date1 > date2 && item.takeAudit == 1) {
        return true;
      } else {
        for (let index = 0; index < this.tableData1.length; index++) {
          if (item.takeId == this.tableData1[index].takeId) {
            this.tableData1.splice(index, 1);
          }
        }
        this.tableData = this.tableData1.slice(0, 12);
        this.totalData = this.tableData1.length;
        return false;
      }
    },
    // 弹框
    showDetail(item) {
      this.dialogFormVisible = true;
      console.log(item);
      this.form = item;
      axios({
        methods: "GET",
        url: "http://127.0.0.1:3000/take/takeImg",
        params: {
          takeId: item.takeId, //寻物id
        },
      })
        .then((res) => {
          if (res.data.code == 200) {
            console.log("success", res);
            console.log(res.data.data, "img");
            item.img = res.data.data;
            // that.tableData1 = res.data.data;
          } else {
            console.log("error", res);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      setTimeout(() => {
        this.form = item;
      }, 300);
      console.log(this.form);
    },
    // 留言信息
    takeMessage(data) {
      if (this.identity) {
        this.$prompt("请输入留言内容", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^(?=.*?[\u4E00-\u9FA5]){5,100}/,
          inputErrorMessage: "不能少于5个字符,必须有汉字",
        })
          .then(({ value }) => {
            // 留言内容
            data.leaveMessage = {};
            data.leaveMessage[window.sessionStorage.getItem("userId")] =
              window.sessionStorage.getItem("userName") + "给你留言: " + value;
            this.$message({
              type: "success",
              message: "你的留言信息是: " + value,
            });
            console.log(data);
            this.dialogFormVisible = false;
            axios({
              methods: "get",
              url: "http://127.0.0.1:3000/take/updateTake",
              params: {
                takeId: data.takeId, //寻物id
                leaveMessage:
                  data.leaveMessage[window.sessionStorage.getItem("userId")],
                userId: window.sessionStorage.getItem("userId"),
                leaveUser: window.sessionStorage.getItem("userName"),
              },
            })
              .then((data) => {
                console.log(data);
              })
              .catch((err) => {
                console.log(err);
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消输入",
            });
          });
      } else {
        this.$message.error("您还未登录，无法进行该操作");
      }
    },
    // 举报
    jubao(data) {
      if (this.identity) {
        this.$prompt(
          "请输入举报原因",
          "请如实填写举报，经由管理员审核后会对用户进行信息发布的限制",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputPattern: /^(?=.*?[\u4E00-\u9FA5])/,
            inputErrorMessage: "必须有汉字",
          }
        )
          .then(({ value }) => {
            data.jubao = {};
            data.jubao[window.sessionStorage.getItem("userId")] = value;
            this.$message({
              type: "success",
              message: "已收到你的举报信息 ",
            });
            axios({
              methods: "get",
              url: "http://127.0.0.1:3000/take/jubaoTake",
              params: {
                takeId: data.takeId, //寻物id
                jubao: data.jubao[window.sessionStorage.getItem("userId")],
                userId: window.sessionStorage.getItem("userId"),
              },
            })
              .then((data) => {
                console.log(data);
              })
              .catch((err) => {
                console.log(err);
              });
            // console.log(data);
            this.dialogFormVisible = false;
            window.location.reload();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消输入",
            });
          });
      } else {
        this.$message.error("您还未登录，无法进行该操作");
      }
    },
    // add
    // 图片
    handleChange(file, fileList) {
      // console.log(file, fileList);
      //  const image = new Image() // 新建一个img标签（还没嵌入DOM节点)
      //       //blob:http://localhost:8080/b878edea-e649-4f8d-b723-c3f25454141b
      //       image.src = file.url;
      //       image.onload = () => {
      //         const canvas = document.createElement('canvas')
      //         canvas.width = image.width
      //         canvas.height = image.height
      //         const context = canvas.getContext('2d')
      //         context.drawImage(image, 0, 0, image.width, image.height);
      //         let imgUrl = canvas.toDataURL() //图片的base64地址
      //         console.log(imgUrl,22);
      //       }

      for (let i = 0; i < fileList.length; i++) {
        // fileList[0].url = "blob:http://localhost:8080/b18b3167-8b01-4652-8440-48a14a0aa9fc"
        fetch(fileList[i].url)
          .then((data) => {
            const blob = data.blob();
            console.log(blob);
            return blob;
          })
          .then((blob) => {
            let reader = new window.FileReader();
            reader.onloadend = function () {
              const data = reader.result;
              fileList[i].url = data;
            };
            reader.readAsDataURL(blob);
          });
      }
      var img = [];
      setTimeout(() => {
        for (let index = 0; index < fileList.length; index++) {
          img.push(fileList[index].url);
        }
        console.log(img);
      }, 300);
      this.fileList = img;
    },
    //base64 转blob
    //   dataURLtoBlob(dataurl) {
    //         var arr = dataurl.split(','),
    //             mime = arr[0].match(/:(.*?);/)[1],
    //             bstr = atob(arr[1]),
    //             n = bstr.length,
    //             u8arr = new Uint8Array(n)
    //         while (n--) {
    //             u8arr[n] = bstr.charCodeAt(n)
    //         }
    //         return new Blob([u8arr], { type: mime })
    //     },
    //     // blob转base64
    //      blobToDataURL(blob, callback) {
    //         let a = new FileReader()
    //         a.onload = function (e) {
    //             callback(e.target.result)
    //         }
    //         a.readAsDataURL(blob)
    //         // return a;
    // },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    queryTitleSearch(queryString, cb) {
      var restaurants = this.loadAllTitle;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    queryPlaceSearch(queryString, cb) {
      var restaurants = this.loadAllPlace;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      console.log(item);
      // this.addTag(item.value);
    },
    hidden() {
      //处理close
      this.addInfo = false;
      (this.addform = {
        tagType: "",
        validDate: this.formatDate(new Date()),
      }),
        (this.dynamicTags = []);
      this.inputValue = "";
    },
    add(formName, item) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log("submit!");
          item.tagType = "代取";
          item.tags = this.dynamicTags.join(",");
          item.img = this.fileList;
          var takeId = 0;
          axios
            .post("http://127.0.0.1:3000/take/addTake", {
              InfoPublisher: window.sessionStorage.getItem("userName"),
              takeAudit: 1,
              takeContent: item.contact,
              takeDesc: item.desc,
              takeImg: item.img[0],
              // takeTagType: item.tagType,
              takeTags: item.tags,
              takeTitle: item.title,
              takeType: "代取",
              takeValidDate: item.validDate,
              leaveMessageAudit: 0,
            })
            .then((data) => {
              takeId = data.data.data.insertId;
              console.log(takeId);
            })
            .catch((err) => {
              console.log(err);
              this.$message.error("图片过大，请再次尝试");
            });

          setTimeout(() => {
            console.log(takeId, "takeId");
            axios
              .post("http://127.0.0.1:3000/take/addTakeImgs", {
                takeId: takeId,
                takeImgs: item.img,
              })
              .then((data) => {
                console.log(data, 1);
              })
              .catch((err) => {
                console.log(err);
                this.$message.error("图片过大，请再次尝试");
              });
            window.location.reload();
          }, 1300);
          this.addInfo = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 新tag
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    addTag(value) {
      // console.log(value);
      let inputValue = value;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 搜索
    searchData(data) {
      var that = this;
      if (data.length != 0) {
        axios({
          methods: "GET",
          url: "http://127.0.0.1:3000/take/searchTitle",
          params: {
            searchTitle: data,
          },
        })
          .then((res) => {
            console.log("success", res);
            console.log(res.data.data);
            this.tableData1 = res.data.data;
          })
          .catch((err) => {
            console.log(err);
          });
        setTimeout(() => {
          for (let index = 0; index < that.tableData1.length; index++) {
            if (typeof that.tableData1[index].takeTags == "string") {
              var chars = that.tableData1[index].takeTags.split(",");
              that.tableData1[index].takeTags = chars;
            } else if (that.tableData1[index].takeTags == null) {
              that.tableData1[index].takeTags = ["暂无标签"];
            }
          }
          this.tableData = this.tableData1.slice(0, 12);
          this.totalData = this.tableData1.length;
        }, 200);
      } else {
        that.getData();
      }
    },
  },
};
</script>

<style scoped lang="css">
.desc {
  overflow-y: hidden;
  height: 45px;
  font-size: 13px;
  color: #999;
  width: 100%;
  border: none;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  resize: none;
}
.time {
  display: block;
  padding-top: 8px;
  font-size: 13px;
  color: #999;
}
.bottom {
  margin-top: 8px;
  line-height: 12px;
}

.button {
  padding: 0;
  /* float: right; */
  position: absolute;
  right: 7px;
  bottom: 8px;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.tags {
  margin-top: 8px;
}
.tags .el-tag {
  margin: 3px;
}
.el-card {
  height: 370px;
  position: relative;
}
.pages {
  position: fixed;
  bottom: 10px;
  right: 10px;
}
/* 新tag */
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
/* 举报样式 */
.el-message-box__title {
  color: red !important;
  font-size: 9px !important;
}
</style>